<?php
Namespace Cyfy\Modules\Forms;
use Cyfy\Message;

/**
 * Creates a new tabset element.
 *
 * Usage:
 * <code>
 * // called in method structure() of a form, that's why there is $this
 *
 * $f = new Forms\tabset('tabset01','My great field set.');
 *
 * $i = new Forms\TextBox('username', 'Username');
 * $i -> required = true;
 * $i -> maxLength = 50;
 * $f -> addItem($i);
 *
 * $this -> addItem($f);
 * 
 * // some other items can be added directly
 * $i = new Forms\TextBox('aText', 'Some kind of a textbox');
 * $this -> addItem($i);
 *
 * </code>
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
class TabSet extends Input
{
    /**
     * Objects, which the tabset contains.
     * @var array
     */
    private $contents = array();
    private $contentsTabs = array();
    private $tabs = array();
    
    /**
     * Tab name, which is shown by default. 
     */
    public $defaultTab = '';
    
    /**
     * Creates a new tabset.
     * @param string tabset codename.
     * @param string Title of the tabset.
     */
    function __construct($name, $title = "")
    {
        $this -> name = $name;
        $this -> title = $title;
    }
    
    /**
     * Creates a new tab
     * @param string Code - ID - string without white space
     * @param string Name - title.
     */
    function addTab($code, $name)
    {
        $this -> tabs[$code] = $name;
    }
    
    /**
     * Adds an item into buffer.
     * @param string Tab code.
     * @param object Instance of class derived from \Cyfy\Modules\Forms\Input
     */
    public function addItem($tab, $object)
    {
        $object -> inFieldset = true;
        $this -> contents[$object->name] = $object;
        $this -> contentsTabs[$tab][$object->name] = $object;
    }
    
    /**
     * Returns its contents.
     * @return array
     */
    public function getContents()
    {
        return $this -> contents;        
    }
    
    /**
     * Returns serialized tabset.
     * @return string HTML code.
     */
    function __toString()
    {
        $tabs = new \Cyfy\Modules\Objects\Tabs();
        $tabs -> setDefault($this -> defaultTab);
        
        // inputs
        foreach($this -> tabs as $code => $title)
        {
            $contents = "";
            foreach($this -> contentsTabs[$code] as $object)
            {
                $contents .= $object -> __toString();
            }
            $tabs -> addTab($code, $title, $contents);
        }
        
        
        return $tabs -> show();
    }

}